package regions

import (
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"product/common/datetime"
	"product/common/enumeration"
	"product/common/toolbox"
	"product/common/validator"
	"product/settings/model/regions"
	"product/settings/serve/internal/svc"
	"product/settings/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddRegionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAddRegionLogic add regions
func NewAddRegionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddRegionLogic {
	return &AddRegionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddRegionLogic) AddRegion(req *types.AddAreaReq) (resp *types.AddAreaResp, err error) {
	ok, err := validInputAdd(req)
	if !ok && err != nil {
		return &types.AddAreaResp{
			Code:    enumeration.ProcessingFailed,
			Message: err.Error(),
		}, err
	}
	err = l.svcCtx.RegionsModel.Trans(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		_, err = l.svcCtx.RegionsModel.FindOneByCode(ctx, req.Code)
		if err == nil {
			return errors.New("code已存在")
		}
		_, err = l.svcCtx.RegionsModel.FindOneByName(ctx, req.Name)
		if err == nil {
			return errors.New("name已存在")
		}
		areaId := toolbox.GetUniqueId()
		_, err = l.svcCtx.RegionsModel.Insert(ctx, &regions.Regions{
			Code:      req.Code,
			Name:      req.Name,
			Level:     int64(req.Level),
			ParentId:  req.ParentId,
			CreatedAt: datetime.GetNowTimestamp(),
			UpdatedAt: datetime.GetNowTimestamp(),
			ID:        areaId,
		})
		return err
	})

	if err != nil {
		return &types.AddAreaResp{
			Code:    enumeration.ProcessingFailed,
			Message: err.Error(),
		}, err
	}
	return &types.AddAreaResp{
		Code:    enumeration.ProcessingSuccess,
		Message: "添加成功",
	}, nil
}

func validInputAdd(req *types.AddAreaReq) (bool, error) {
	if validator.IsEmptyString(req.Code) {
		return false, errors.New("code不能为空")
	}
	if validator.IsEmptyString(req.Name) {
		return false, errors.New("name不能为空")
	}
	if req.Level < 1 || req.Level > 4 {
		return false, errors.New("level值在1-4之间")
	}
	return true, nil
}
